# -*- coding: UTF-8 -*-

import datetime
import sys
from sqlalchemy import and_,  func, or_
from typing import Dict, List, Any, Generator

from sqlalchemy import Boolean, Column, DateTime, Integer, String, Index, Table, ForeignKey, text, JSON, TEXT, distinct
from sqlalchemy.orm import Session, relationship
from common.database import Base
from common.database import SessionMixin
from app.monitor_metrics.models.prom_alarm_group import PromAlarmGroup
from app.monitor_metrics.models.prom_alarm_rule import PromAlarmRule
from common.utils import is_empty
from core.logger import logger

__all__ = ['PromAlarmSet']

class PromAlarmSet(Base, SessionMixin):
    '''
    prometheus告警规则集合
    '''
    __tablename__ = "prom_alarm_set"
    name = Column(String(256), nullable=False, index=True, comment='规则集名称')
    # host主机 or k8s容器
    classes = Column(String(128), nullable=False, comment='规则集归类')
    comment = Column(String(256), nullable=True, comment='规则集说明')

    alarm_groups = relationship("PromAlarmGroup", backref="prom_alarm_set")


    __table_args__ = (
        Index('idx_prom_alarm_set_name', 'name', unique=True),
        {
            'mysql_engine': 'innodb',
            'mysql_charset': 'utf8mb4',
            'mysql_collate': 'utf8mb4_unicode_ci',
            'extend_existing': True,
            'mysql_row_format': 'dynamic'
        }
    )

    def __repr__(self):
        return f"<prom_alarm_set='{self.name}>"


    def object_to_dict(self, db: Session):
        result = {
            key: getattr(self, key)
            for key in self.__mapper__.c.keys()
        }
        result["alarm_groups"] = [
            alarm_group.object_to_dict(db)
            for alarm_group in self.alarm_groups
        ]

        return result


    @classmethod
    def get_object_info_by_alarm_metrics(cls, db: Session, alarm_metrics_uuid: int):
        alarm_sets_info = db.query(cls).join(PromAlarmGroup).join(PromAlarmRule).filter(
            PromAlarmRule.alarm_metrics_uuid == alarm_metrics_uuid
        ).all()

        result = [
            cls.get_object_info_by_uuid(db, item.uuid)
            for item in alarm_sets_info
        ]

        return result


    @classmethod
    def get_object_info_by_light(cls, db: Session, uuid: int):
        object_info = db.query(cls).filter(
            cls.uuid == uuid
        ).to_dict_first()

        return object_info

    @classmethod
    def get_object_infos_by_light(cls, db: Session):
        object_info = db.query(cls).to_dict()

        return object_info
